﻿using DongFangGuoKai.WMSPlatform.Commn.ApiResultModule;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace DongFangGuoKai.WMSPlatform.WebApi.Utility.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class GlobalExceptionHandler : IAsyncExceptionFilter
    {
        private readonly ILogger<GlobalExceptionHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger">log</param>
        public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
        {
            this.logger = logger;
        }
        /// <summary>
        /// 全局异常处理
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                ApiBaseResult result = new ApiBaseResult();
                result.Code = 500;
                result.Msg = "异常：" + context.Exception.Message;
                context.Result = new JsonResult(result);
                context.ExceptionHandled = true;  //标注下当前这个异常已经处理过了

                logger.LogError(result.Msg);
            }
            return Task.CompletedTask;
        }
    }
}
